package com.jqh.androidlockdemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.provider.MediaStore;

import java.util.List;

public class PlayerService extends Service {
    private MediaPlayer mp;
    private Mp3Application application;
    private List<Song> songs;
    private int songItemPos;

    @Override
    public void onCreate() {
        super.onCreate();
        application = (Mp3Application) getApplication();
        songs = application.songsList;
        application.music = new MusicListener();
        mp = new MediaPlayer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        play(songItemPos);
        return (IBinder) application.music;
    }

    public void play(int position) {
        if(position>=0){
            position=position % application.songsList.size();
        }
        else{
            position = application.songsList.size()+ position;
        }

        application.songItemPos = position;//在全局变量中标记当前播放位置
        Song currentSong = songs.get(position);//获取当前播放音乐
//        Uri musicTableForSD = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//        Uri uri = Uri.withAppendedPath(musicTableForSD,
//                "/" + currentSong.getId());//初始化mp对象
        Uri uri1 = Uri.parse(currentSong.getUrl());
        mp = MediaPlayer.create(this, uri1);

        System.out.println(currentSong.getName());

        try {
            mp.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mp.stop();
        mp.release();
        mp = null;
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    private class MusicListener extends Binder implements IMusic {

        public PlayerService getService()
        {
            return PlayerService.this;
        }
        @Override
        public void moveon() {
            if (mp != null) {
                mp.start();
            }
        }

        @Override
        public void pause() {
            if (mp != null) {
                mp.pause();
            }
        }

        @Override
        public void stop() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
            }
        }

        @Override
        public void nextSong() {
            if (mp != null) {
                mp.stop();
            }
            play(++application.songItemPos);
        }

        @Override
        public void lastSong() {
            if (mp != null) {
                mp.stop();
            }
            play(--application.songItemPos);
        }
    }

}
